diff --git a/install/recoverFilesToVideos.php b/install/recoverFilesToVideos.php
index 411fdf53e..2c12a1b28 100644
--- a/install/recoverFilesToVideos.php
+++ b/install/recoverFilesToVideos.php
@@ -1,73 +1,73 @@
$value) {
$video = Video::getVideoFromFileName($value[0], true);
if (!empty($video)) {
unset($files[$key]);
}
}
echo "*** Total filenames " . $total . " Will be created\n";
echo "*** Confirm Create Them? y/n: ";
ob_flush();
$confirm = trim(readline(""));
if (!empty($confirm) && strtolower($confirm) === 'y') {
$count = 0;
foreach ($files as $key => $value) {
$count++;
$title = "Video recovered: ".date("Y-m-d H:i:s", filectime($value[1]));
$video = new Video($title, $value[0]);
- $video->setStatus('a');
+ $video->setStatus(Video::$statusActive);
$video->setUsers_id(1);
if($video->save(false, true)){
echo "{$count}/{$total} {$title} created\n";
}else{
echo "{$count}/{$total} ERROR on create video {$title}\n";
}
}
}
\ No newline at end of file
diff --git a/objects/Object.php b/objects/Object.php
index 064e756fa..15b8a9372 100644
--- a/objects/Object.php
+++ b/objects/Object.php
@@ -1,649 +1,654 @@
load($id);
}
}
protected function load($id) {
$row = self::getFromDb($id);
if (empty($row)) {
return false;
}
foreach ($row as $key => $value) {
$this->$key = $value;
}
return true;
}
public static function getNowFromDB() {
global $global;
$sql = "SELECT NOW() as my_date_field";
$res = sqlDAL::readSql($sql);
$data = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res) {
$row = $data;
} else {
$row = false;
}
return $row;
}
public static function setTimeZone() {
global $advancedCustom;
$row = self::getNowFromDB();
$dt = new DateTime($row['my_date_field']);
- $timeZOnesOptions = object_to_array($advancedCustom->timeZone->type);
- if (empty($timeZOnesOptions[$advancedCustom->timeZone->value])) {
+ if(!empty($_COOKIE['timezone'])){
+ $timezone = $_COOKIE['timezone'];
+ }else{
+ $timeZOnesOptions = object_to_array($advancedCustom->timeZone->type);
+ $timezone = $timeZOnesOptions[$advancedCustom->timeZone->value];
+ }
+ if (empty($timezone)) {
return false;
}
try {
- $objDate = new DateTimeZone($timeZOnesOptions[$advancedCustom->timeZone->value]);
+ $objDate = new DateTimeZone($timezone);
if (is_object($objDate)) {
$dt->setTimezone($objDate);
- date_default_timezone_set($timeZOnesOptions[$advancedCustom->timeZone->value]);
+ date_default_timezone_set($timezone);
return $dt;
}
return false;
} catch (Exception $exc) {
_error_log("setTimeZone: " . $exc->getMessage(), AVideoLog::$ERROR);
return false;
}
}
protected static function getFromDb($id) {
global $global;
$id = intval($id);
$sql = "SELECT * FROM " . static::getTableName() . " WHERE id = ? LIMIT 1";
// I had to add this because the about from customize plugin was not loading on the about page http://127.0.0.1/AVideo/about
$res = sqlDAL::readSql($sql, "i", array($id), true);
$data = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res) {
$row = $data;
} else {
$row = false;
}
return $row;
}
public static function getAll() {
global $global;
if (!static::isTableInstalled()) {
return false;
}
$sql = "SELECT * FROM " . static::getTableName() . " WHERE 1=1 ";
$sql .= self::getSqlFromPost();
$res = sqlDAL::readSql($sql);
$fullData = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
$rows = array();
if ($res != false) {
foreach ($fullData as $row) {
$rows[] = $row;
}
} else {
die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
return $rows;
}
public static function getAllActive() {
global $global;
if (!static::isTableInstalled()) {
return false;
}
$sql = "SELECT * FROM " . static::getTableName() . " WHERE status='a' ";
$sql .= self::getSqlFromPost();
$res = sqlDAL::readSql($sql);
$fullData = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
$rows = array();
if ($res != false) {
foreach ($fullData as $row) {
$rows[] = $row;
}
} else {
die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
return $rows;
}
public static function getTotal() {
//will receive
//current=1&rowCount=10&sort[sender]=asc&searchPhrase=
global $global;
if (!static::isTableInstalled()) {
return 0;
}
$sql = "SELECT id FROM " . static::getTableName() . " WHERE 1=1 ";
$sql .= self::getSqlSearchFromPost();
$res = sqlDAL::readSql($sql);
$countRow = sqlDAL::num_rows($res);
sqlDAL::close($res);
return $countRow;
}
public static function getSqlFromPost($keyPrefix = "") {
global $global;
$sql = self::getSqlSearchFromPost();
if (empty($_POST['sort']) && !empty($_GET['order'][0]['dir'])) {
$index = intval($_GET['order'][0]['column']);
$_GET['columns'][$index]['data'];
$_POST['sort'][$_GET['columns'][$index]['data']] = $_GET['order'][0]['dir'];
}
// add a security here
if (!empty($_POST['sort'])) {
foreach ($_POST['sort'] as $key => $value) {
$_POST['sort'][xss_esc($key)] = xss_esc($value);
}
}
if (!empty($_POST['sort'])) {
$orderBy = array();
foreach ($_POST['sort'] as $key => $value) {
$key = $global['mysqli']->real_escape_string($key);
//$value = $global['mysqli']->real_escape_string($value);
$direction = "ASC";
if (strtoupper($value) === "DESC") {
$direction = "DESC";
}
$key = preg_replace("/[^A-Za-z0-9._ ]/", '', $key);
$orderBy[] = " {$keyPrefix}{$key} {$value} ";
}
$sql .= " ORDER BY " . implode(",", $orderBy);
}
$sql .= self::getSqlLimit();
return $sql;
}
public static function getSqlLimit() {
global $global;
$sql = "";
if (empty($_POST['rowCount']) && !empty($_GET['length'])) {
$_POST['rowCount'] = intval($_GET['length']);
}
if (empty($_POST['current']) && !empty($_GET['start'])) {
$_POST['current'] = ($_GET['start'] / $_GET['length']) + 1;
} elseif (empty($_POST['current']) && isset($_GET['start'])) {
$_POST['current'] = 1;
}
$_POST['current'] = getCurrentPage();
$_POST['rowCount'] = getRowCount();
if (!empty($_POST['rowCount']) && !empty($_POST['current']) && $_POST['rowCount'] > 0) {
$_POST['rowCount'] = intval($_POST['rowCount']);
$_POST['current'] = intval($_POST['current']);
$current = ($_POST['current'] - 1) * $_POST['rowCount'];
$current = $current < 0 ? 0 : $current;
$sql .= " LIMIT $current, {$_POST['rowCount']} ";
} else {
$_POST['current'] = 0;
$_POST['rowCount'] = 0;
$sql .= " LIMIT 1000 ";
}
return $sql;
}
public static function getSqlSearchFromPost() {
$sql = "";
if (!empty($_POST['searchPhrase'])) {
$_GET['q'] = $_POST['searchPhrase'];
} elseif (!empty($_GET['search']['value'])) {
$_GET['q'] = $_GET['search']['value'];
}
if (!empty($_GET['q'])) {
global $global;
$search = $global['mysqli']->real_escape_string(xss_esc($_GET['q']));
$like = array();
$searchFields = static::getSearchFieldsNames();
foreach ($searchFields as $value) {
$like[] = " {$value} LIKE '%{$search}%' ";
// for accent insensitive
$like[] = " CONVERT(CAST({$value} as BINARY) USING utf8) LIKE '%{$search}%' ";
}
if (!empty($like)) {
$sql .= " AND (" . implode(" OR ", $like) . ")";
} else {
$sql .= " AND 1=1 ";
}
}
return $sql;
}
public function save() {
if (!$this->tableExists()) {
_error_log("Save error, table " . static::getTableName() . " does not exists", AVideoLog::$ERROR);
return false;
}
global $global;
$fieldsName = $this->getAllFields();
if (!empty($this->id)) {
$sql = "UPDATE " . static::getTableName() . " SET ";
$fields = array();
foreach ($fieldsName as $value) {
if (strtolower($value) == 'created') {
// do nothing
} elseif (strtolower($value) == 'modified') {
$fields[] = " {$value} = now() ";
} elseif (is_numeric($this->$value)) {
$fields[] = " `{$value}` = {$this->$value} ";
} elseif (strtolower($this->$value) == 'null') {
$fields[] = " `{$value}` = NULL ";
} else {
$fields[] = " `{$value}` = '{$this->$value}' ";
}
}
$sql .= implode(", ", $fields);
$sql .= " WHERE id = {$this->id}";
} else {
$sql = "INSERT INTO " . static::getTableName() . " ( ";
$sql .= "`" . implode("`,`", $fieldsName) . "` )";
$fields = array();
foreach ($fieldsName as $value) {
if (strtolower($value) == 'created' || strtolower($value) == 'modified') {
$fields[] = " now() ";
} elseif (!isset($this->$value) || strtolower($this->$value) == 'null') {
$fields[] = " NULL ";
} else {
$fields[] = " '{$this->$value}' ";
}
}
$sql .= " VALUES (" . implode(", ", $fields) . ")";
}
//if(static::getTableName() == 'subscriptions') echo $sql;
$insert_row = sqlDAL::writeSql($sql);
if ($insert_row) {
if (empty($this->id)) {
$id = $global['mysqli']->insert_id;
} else {
$id = $this->id;
}
return $id;
} else {
_error_log("ObjectYPT::save Error on save: " . $sql . ' Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error, AVideoLog::$ERROR);
return false;
}
}
private function getAllFields() {
global $global, $mysqlDatabase;
$sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = '" . static::getTableName() . "'";
$res = sqlDAL::readSql($sql, "s", array($mysqlDatabase));
$fullData = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
$rows = array();
if ($res != false) {
foreach ($fullData as $row) {
$rows[] = $row["COLUMN_NAME"];
}
} else {
die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
return $rows;
}
public function delete() {
global $global;
if (!empty($this->id)) {
$sql = "DELETE FROM " . static::getTableName() . " ";
$sql .= " WHERE id = ?";
$global['lastQuery'] = $sql;
//_error_log("Delete Query: ".$sql);
return sqlDAL::writeSql($sql, "i", array($this->id));
}
_error_log("Id for table " . static::getTableName() . " not defined for deletion", AVideoLog::$ERROR);
return false;
}
public static function setCache($name, $value) {
$cachefile = self::getCacheFileName($name);
make_path($cachefile);
$content = _json_encode($value);
if(empty($content)){
$content = $value;
}
$bytes = @file_put_contents($cachefile, $content);
self::setSessionCache($name, $value);
return array('bytes' => $bytes, 'cachefile' => $cachefile);
}
public static function cleanCacheName($name) {
$name = str_replace(array('/', '\\'), array(DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR), $name);
$name = preg_replace('/[!#$&\'()*+,:;=?@[\\]% -]+/', '_', trim(strtolower(cleanString($name))));
$name = preg_replace('/\/{2,}/', '/', trim(strtolower(cleanString($name))));
if (function_exists('mb_ereg_replace')) {
$name = mb_ereg_replace("([^\w\s\d\-_~,;\[\]\(\).\\/\\\])", '', $name);
// Remove any runs of periods (thanks falstro!)
$name = mb_ereg_replace("([\.]{2,})", '', $name);
}
return preg_replace('/[\x00-\x1F\x7F]/u', '', $name);
}
/**
*
* @param type $name
* @param type $lifetime, if is = 0 it is unlimited
* @return type
*/
public static function getCache($name, $lifetime = 60, $ignoreSessionCache = false) {
if (isCommandLineInterface()) {
return false;
}
global $getCachesProcessed, $_getCache;
if (empty($_getCache)) {
$_getCache = array();
}
if (empty($getCachesProcessed)) {
$getCachesProcessed = array();
}
$cachefile = self::getCacheFileName($name);
if (!empty($_getCache[$name])) {
return $_getCache[$name];
}
if (empty($getCachesProcessed[$name])) {
$getCachesProcessed[$name] = 0;
}
$getCachesProcessed[$name]++;
if (!empty($_GET['lifetime'])) {
$lifetime = intval($_GET['lifetime']);
}
if (empty($ignoreSessionCache)) {
$session = self::getSessionCache($name, $lifetime);
if (!empty($session)) {
$_getCache[$name] = $session;
return $session;
}
}
/*
if (preg_match('/firstpage/i', $cachefile)) {
echo var_dump($cachefile) . PHP_EOL;
$trace = debug_backtrace();
$backtrace_lite = array();
foreach ($trace as $call) {
echo $call['function'] . " " . $call['file'] . " line " . $call['line'] . PHP_EOL;
}exit;
}
/**
*/
if (file_exists($cachefile) && (empty($lifetime) || time() - $lifetime <= filemtime($cachefile))) {
//if(preg_match('/getStats/', $cachefile)){echo $cachefile,'
';}
$c = @url_get_contents($cachefile);
$json = _json_decode($c);
if(empty($json) && !is_object($json) && !is_array($json)){
$json = $c;
}
self::setSessionCache($name, $json);
$_getCache[$name] = $json;
return $json;
} elseif (file_exists($cachefile)) {
self::deleteCache($name);
}
return null;
}
public static function deleteCache($name) {
global $__getAVideoCache;
unset($__getAVideoCache);
$cachefile = self::getCacheFileName($name);
@unlink($cachefile);
self::deleteSessionCache($name);
ObjectYPT::deleteCacheFromPattern($name);
}
static function deleteCachePattern($pattern) {
global $__getAVideoCache;
unset($__getAVideoCache);
$tmpDir = self::getCacheDir();
$array = _glob($tmpDir, $pattern);
foreach ($array as $value) {
_error_log("Object::deleteCachePattern file [{$value}]");
@unlink($value);
}
_session_start();
foreach ($_SESSION['user']['sessionCache'] as $key => $value) {
if (preg_match($pattern, $key)) {
_error_log("Object::deleteCachePattern session [{$key}]");
$_SESSION['user']['sessionCache'][$key] = null;
unset($_SESSION['user']['sessionCache'][$key]);
}
}
}
public static function deleteALLCache() {
global $__getAVideoCache;
unset($__getAVideoCache);
$tmpDir = self::getCacheDir();
rrmdir($tmpDir);
self::deleteAllSessionCache();
self::setLastDeleteALLCacheTime();
}
public static function getCacheDir($filename = '') {
global $_getCacheDir, $global;
if (!isset($_getCacheDir)) {
$_getCacheDir = array();
}
if (!empty($_getCacheDir[$filename])) {
return $_getCacheDir[$filename];
}
$tmpDir = getTmpDir();
$tmpDir = rtrim($tmpDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
$tmpDir .= "YPTObjectCache" . DIRECTORY_SEPARATOR;
$filename = self::cleanCacheName($filename);
if (!empty($filename)) {
$tmpDir .= $filename . DIRECTORY_SEPARATOR;
$domain = getDomain();
$tmpDir .= $domain . DIRECTORY_SEPARATOR;
// make sure you separete http and https cache
$protocol = isset($_SERVER["HTTPS"]) ? 'https' : 'http';
$tmpDir .= $protocol . DIRECTORY_SEPARATOR;
if (class_exists("User_Location")) {
$loc = User_Location::getThisUserLocation();
if (!empty($loc) && !empty($loc['country_code'])) {
$tmpDir .= $loc['country_code'] . DIRECTORY_SEPARATOR;
}
}
if (User::isLogged()) {
if(User::isAdmin()){
$tmpDir .= 'admin_'.md5("admin".$global['salt']).DIRECTORY_SEPARATOR;
}else{
$tmpDir .= 'user_'.md5("user".$global['salt']).DIRECTORY_SEPARATOR;
}
}else{
$tmpDir .= 'notlogged_'.md5("notlogged".$global['salt']).DIRECTORY_SEPARATOR;
}
}
make_path($tmpDir);
if (!file_exists($tmpDir . "index.html") && is_writable($tmpDir)) {// to avoid search into the directory
file_put_contents($tmpDir . "index.html", time());
}
$_getCacheDir[$filename] = $tmpDir;
return $tmpDir;
}
public static function getCacheFileName($name) {
global $global;
$tmpDir = self::getCacheDir($name);
$uniqueHash = md5($name . $global['salt']); // add salt for security reasons
return $tmpDir . $uniqueHash . '.cache';
}
public static function deleteCacheFromPattern($name) {
$tmpDir = getTmpDir();
$name = self::cleanCacheName($name);
$ignoreLocationDirectoryName = (strpos($name, DIRECTORY_SEPARATOR) !== false);
$filePattern = $tmpDir . DIRECTORY_SEPARATOR . $name;
foreach (glob("{$filePattern}*") as $filename) {
unlink($filename);
}
self::deleteSessionCache($name);
}
/**
* Make sure you start the session before any output
* @param type $name
* @param type $value
*/
public static function setSessionCache($name, $value) {
$name = self::cleanCacheName($name);
_session_start();
$_SESSION['user']['sessionCache'][$name]['value'] = json_encode($value);
$_SESSION['user']['sessionCache'][$name]['time'] = time();
if (empty($_SESSION['user']['sessionCache']['time'])) {
$_SESSION['user']['sessionCache']['time'] = time();
}
}
/**
*
* @param type $name
* @param type $lifetime, if is = 0 it is unlimited
* @return type
*/
public static function getSessionCache($name, $lifetime = 60) {
$name = self::cleanCacheName($name);
if (!empty($_GET['lifetime'])) {
$lifetime = intval($_GET['lifetime']);
}
if (!empty($_SESSION['user']['sessionCache'][$name])) {
if ((empty($lifetime) || time() - $lifetime <= $_SESSION['user']['sessionCache'][$name]['time'])) {
$c = $_SESSION['user']['sessionCache'][$name]['value'];
$json = _json_decode($c);
if(is_string($json) && strtolower($json) === 'false'){
$json = false;
}
return $json;
}
_session_start();
unset($_SESSION['user']['sessionCache'][$name]);
}
return null;
}
public static function clearSessionCache() {
unset($_SESSION['user']['sessionCache']);
}
private static function getLastDeleteALLCacheTimeFile() {
$tmpDir = getTmpDir();
$tmpDir = rtrim($tmpDir, DIRECTORY_SEPARATOR) . "/";
$tmpDir .= "lastDeleteALLCacheTime.cache";
return $tmpDir;
}
public static function setLastDeleteALLCacheTime() {
$file = self::getLastDeleteALLCacheTimeFile();
//_error_log("ObjectYPT::setLastDeleteALLCacheTime {$file}");
return file_put_contents($file, time());
}
public static function getLastDeleteALLCacheTime() {
global $getLastDeleteALLCacheTime;
if (empty($getLastDeleteALLCacheTime)) {
$getLastDeleteALLCacheTime = (int) @file_get_contents(self::getLastDeleteALLCacheTimeFile(), time());
}
return $getLastDeleteALLCacheTime;
}
public static function checkSessionCacheBasedOnLastDeleteALLCacheTime() {
/*
var_dump(
$session_var['time'],
self::getLastDeleteALLCacheTime(),
humanTiming($session_var['time']),
humanTiming(self::getLastDeleteALLCacheTime()),
$session_var['time'] <= self::getLastDeleteALLCacheTime());
*
*/
if (empty($_SESSION['user']['sessionCache']['time']) || $_SESSION['user']['sessionCache']['time'] <= self::getLastDeleteALLCacheTime()) {
self::deleteAllSessionCache();
return false;
}
return true;
}
public static function deleteSessionCache($name) {
$name = self::cleanCacheName($name);
_session_start();
$_SESSION['user']['sessionCache'][$name] = null;
unset($_SESSION['user']['sessionCache'][$name]);
}
public static function deleteAllSessionCache() {
_session_start();
unset($_SESSION['user']['sessionCache']);
}
public function tableExists() {
return self::isTableInstalled();
}
public static function isTableInstalled($tableName = "") {
global $global, $tableExists;
if (empty($tableName)) {
$tableName = static::getTableName();
}
if (empty($tableName)) {
return false;
}
if (!isset($tableExists[$tableName])) {
$sql = "SHOW TABLES LIKE '" . $tableName . "'";
//_error_log("isTableInstalled: ({$sql})");
$res = sqlDAL::readSql($sql);
$result = sqlDal::num_rows($res);
sqlDAL::close($res);
$tableExists[$tableName] = !empty($result);
}
return $tableExists[$tableName];
}
}
//abstract class Object extends ObjectYPT{};
diff --git a/objects/aVideoEncoder.json.php b/objects/aVideoEncoder.json.php
index 5b2519c33..c3cf47305 100644
--- a/objects/aVideoEncoder.json.php
+++ b/objects/aVideoEncoder.json.php
@@ -1,229 +1,208 @@
error = true;
global $global, $config;
if (!isset($global['systemRootPath'])) {
require_once '../videos/configuration.php';
}
require_once $global['systemRootPath'] . 'objects/user.php';
require_once $global['systemRootPath'] . 'objects/video.php';
if (empty($_POST)) {
$obj->msg = __("Your POST data is empty, maybe your video file is too big for the host");
_error_log($obj->msg);
die(json_encode($obj));
}
_error_log("aVideoEncoder.json: start");
if (empty($_POST['format']) || !in_array($_POST['format'], $global['allowedExtension'])) {
_error_log("aVideoEncoder.json: Extension not allowed File " . __FILE__ . ": " . json_encode($_POST));
die();
}
// pass admin user and pass
$user = new User("", @$_POST['user'], @$_POST['password']);
$user->login(false, true);
if (!User::canUpload()) {
_error_log("aVideoEncoder.json: Permission denied to receive a file: " . json_encode($_POST));
$obj->msg = __("Permission denied to receive a file: ") . json_encode($_POST);
_error_log($obj->msg);
die(json_encode($obj));
}
if (!empty($_POST['videos_id']) && !Video::canEdit($_POST['videos_id'])) {
_error_log("aVideoEncoder.json: Permission denied to edit a video: " . json_encode($_POST));
$obj->msg = __("Permission denied to edit a video: ") . json_encode($_POST);
_error_log($obj->msg);
die(json_encode($obj));
}
_error_log("aVideoEncoder.json: start to receive: " . json_encode($_POST));
// check if there is en video id if yes update if is not create a new one
$video = new Video("", "", @$_POST['videos_id']);
if(!empty($video->getId()) && !empty($_REQUEST['first_request'])){
_error_log("aVideoEncoder.json: There is a new video to replace the existing one, we will delete the current files videos_id = ".$video->getId());
$video->removeVideoFiles();
}
$obj->video_id = @$_POST['videos_id'];
$title = $video->getTitle();
$description = $video->getDescription();
if (empty($title) && !empty($_POST['title'])) {
$title = $video->setTitle($_POST['title']);
} elseif (empty($title)) {
$video->setTitle("Automatic Title");
}
if (empty($description)) {
$video->setDescription($_POST['description']);
}
if(!empty($_REQUEST['duration'])){
$duration = $video->getDuration();
if(empty($duration) || $duration === 'EE:EE:EE'){
$video->setDuration($_REQUEST['duration']);
}
}
-$status = $video->getStatus();
-// if encoder requested a status
-if (!empty($_POST['overrideStatus'])) {
- $video->setStatus($_POST['overrideStatus']);
-} else { // encoder did not provide a status
- // if status is not unlisted
- if ($status !== 'u' && $status !== 'a') {
- if (empty($advancedCustom->makeVideosInactiveAfterEncode)) {
- // set active or active+encoding
- if (!empty($_POST['keepEncoding'])) {
- $video->setStatus('k');
- } else {
- $video->setStatus('a');
- }
-
- } elseif (empty($advancedCustom->makeVideosUnlistedAfterEncode)) {
- // set active
- $video->setStatus('u');
- } else {
- $video->setStatus('i');
- }
- }
-}
+$status = $video->setAutoStatus();
+
$video->setVideoDownloadedLink($_POST['videoDownloadedLink']);
_error_log("aVideoEncoder.json: Encoder receiving post " . json_encode($_POST));
//_error_log(print_r($_POST, true));
if (preg_match("/(mp3|wav|ogg)$/i", $_POST['format'])) {
$type = 'audio';
$video->setType($type);
} elseif (preg_match("/(mp4|webm|zip)$/i", $_POST['format'])) {
$type = 'video';
$video->setType($type);
}
$videoFileName = $video->getFilename();
if (empty($videoFileName)) {
$mainName = preg_replace("/[^A-Za-z0-9]/", "", cleanString($title));
$videoFileName = uniqid($mainName . "_YPTuniqid_", true);
$video->setFilename($videoFileName);
}
$destination_local = Video::getStoragePath()."{$videoFileName}";
if (!empty($_FILES)) {
_error_log("aVideoEncoder.json: Files " . json_encode($_FILES));
} else {
_error_log("aVideoEncoder.json: Files EMPTY");
if (!empty($_REQUEST['downloadURL'])) {
$_FILES['video']['tmp_name'] = downloadVideoFromDownloadURL($_REQUEST['downloadURL']);
if (empty($_FILES['video']['tmp_name'])) {
_error_log("aVideoEncoder.json: ******** Download ERROR " . $_REQUEST['downloadURL']);
}
}
}
if (!empty($_FILES['video']['error'])) {
$phpFileUploadErrors = array(
0 => 'There is no error, the file uploaded with success',
1 => 'The uploaded file exceeds the upload_max_filesize directive in php.ini',
2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
3 => 'The uploaded file was only partially uploaded',
4 => 'No file was uploaded',
6 => 'Missing a temporary folder',
7 => 'Failed to write file to disk.',
8 => 'A PHP extension stopped the file upload.',
);
_error_log("aVideoEncoder.json: ******** Files ERROR " . $phpFileUploadErrors[$_FILES['video']['error']]);
if (!empty($_POST['downloadURL'])) {
$_FILES['video']['tmp_name'] = downloadVideoFromDownloadURL($_POST['downloadURL']);
}
}
if (empty($_FILES['video']['tmp_name']) && !empty($_POST['chunkFile'])) {
$_FILES['video']['tmp_name'] = $_POST['chunkFile'];
}
// get video file from encoder
if (!empty($_FILES['video']['tmp_name'])) {
$resolution = "";
if (!empty($_POST['resolution'])) {
$resolution = "_{$_POST['resolution']}";
}
$filename = "{$videoFileName}{$resolution}.{$_POST['format']}";
$fsize = filesize($_FILES['video']['tmp_name']);
_error_log("aVideoEncoder.json: receiving video upload to {$filename} filesize=" . ($fsize) . " (" . humanFileSize($fsize) . ")" . json_encode($_FILES));
decideMoveUploadedToVideos($_FILES['video']['tmp_name'], $filename);
} else {
// set encoding
- $video->setStatus('e');
+ $video->setStatus(Video::$statusEncoding);
}
if (!empty($_FILES['image']['tmp_name']) && !file_exists("{$destination_local}.jpg")) {
if (!move_uploaded_file($_FILES['image']['tmp_name'], "{$destination_local}.jpg")) {
$obj->msg = print_r(sprintf(__("Could not move image file [%s.jpg]"), $destination_local), true);
_error_log("aVideoEncoder.json: " . $obj->msg);
die(json_encode($obj));
}
}
if (!empty($_FILES['gifimage']['tmp_name']) && !file_exists("{$destination_local}.gif")) {
if (!move_uploaded_file($_FILES['gifimage']['tmp_name'], "{$destination_local}.gif")) {
$obj->msg = print_r(sprintf(__("Could not move gif image file [%s.gif]"), $destination_local), true);
_error_log("aVideoEncoder.json: " . $obj->msg);
die(json_encode($obj));
}
}
if (!empty($_POST['encoderURL'])) {
$video->setEncoderURL($_POST['encoderURL']);
}
if (!empty($_POST['categories_id'])) {
$video->setCategories_id($_POST['categories_id']);
}
$video_id = $video->save();
$video->updateDurationIfNeed();
$video->updateHLSDurationIfNeed();
if (!empty($_POST['usergroups_id'])) {
if (!is_array($_POST['usergroups_id'])) {
$_POST['usergroups_id'] = array($_POST['usergroups_id']);
}
UserGroups::updateVideoGroups($video_id, $_POST['usergroups_id']);
}
$obj->error = false;
$obj->video_id = $video_id;
_error_log("aVideoEncoder.json: Files Received for video {$video_id}: " . $video->getTitle());
die(json_encode($obj));
/*
_error_log(print_r($_POST, true));
_error_log(print_r($_FILES, true));
var_dump($_POST, $_FILES);
*/
function downloadVideoFromDownloadURL($downloadURL)
{
global $global;
_error_log("aVideoEncoder.json: Try to download " . $downloadURL);
$file = url_get_contents($_POST['downloadURL']);
if (strlen($file)<20000) {
//it is not a video
return false;
}
_error_log("aVideoEncoder.json: Got the download " . $downloadURL);
if ($file) {
$_FILES['video']['name'] = basename($downloadURL);
$temp = Video::getStoragePath()."cache/tmpFile/" . $_FILES['video']['name'];
_error_log("aVideoEncoder.json: save " . $temp);
make_path($temp);
file_put_contents($temp, $file);
return $temp;
}
return false;
}
diff --git a/objects/aVideoEncoderNotifyIsDone.json.php b/objects/aVideoEncoderNotifyIsDone.json.php
index b46e3a5ea..856bbc288 100644
--- a/objects/aVideoEncoderNotifyIsDone.json.php
+++ b/objects/aVideoEncoderNotifyIsDone.json.php
@@ -1,84 +1,68 @@
error = true;
global $global, $config;
if(!isset($global['systemRootPath'])){
require_once '../videos/configuration.php';
}
require_once $global['systemRootPath'] . 'objects/user.php';
require_once $global['systemRootPath'] . 'objects/video.php';
$_POST['videos_id'] = intval($_POST['videos_id']);
if (empty($_POST)) {
$obj->msg = __("Your POST data is empty, maybe your video file is too big for the host");
_error_log($obj->msg);
die(json_encode($obj));
}
// pass admin user and pass
$user = new User("", @$_POST['user'], @$_POST['password']);
$user->login(false, true);
if (!User::canUpload()) {
$obj->msg = __("Permission denied to Notify Done: ") . print_r($_POST, true);
_error_log($obj->msg);
die(json_encode($obj));
}
if(!Video::canEdit($_POST['videos_id'])){
$obj->msg = __("Permission denied to edit a video: ") . print_r($_POST, true);
_error_log($obj->msg);
die(json_encode($obj));
}
Video::clearCache($_POST['videos_id']);
// check if there is en video id if yes update if is not create a new one
$video = new Video("", "", $_POST['videos_id']);
$obj->video_id = $_POST['videos_id'];
-if(empty($_POST['fail'])){
- // if encoder requested a status
- if (!empty($_POST['overrideStatus'])) {
- $video->setStatus($_POST['overrideStatus']);
- } else { // encoder did not provide a status
- $status = $video->getStatus();
- // if status is not unlisted
- if($status!=='u' && $status !== 'a'){
- if(empty($advancedCustom->makeVideosInactiveAfterEncode)){
- // set active
- $video->setStatus('a');
- }else if(empty($advancedCustom->makeVideosUnlistedAfterEncode)){
- // set active
- $video->setStatus('u');
- }else{
- $video->setStatus('i');
- }
- }
- }
-}else{
- $video->setStatus('i');
-}
+
+$video->setAutoStatus(Video::$statusActive);
+
$video_id = $video->save();
-if(empty($_POST['fail'])){
- AVideoPlugin::afterNewVideo($_POST['videos_id']);
+
+$video = new Video("", "", $video_id);
+
+if($video->getStatus() === Video::$statusActive){
+ AVideoPlugin::afterNewVideo($video_id);
}
$obj->error = false;
$obj->video_id = $video_id;
Video::updateFilesize($video_id);
// delete original files if any
$originalFilePath = Video::getStoragePath()."original_" . $video->getFilename();
if(file_exists($originalFilePath)){
unlink($originalFilePath);
}
_error_log("Video is done notified {$video_id}: " . $video->getTitle());
Video::clearCache($video_id);
die(json_encode($obj));
/*
_error_log(print_r($_POST, true));
_error_log(print_r($_FILES, true));
var_dump($_POST, $_FILES);
*/
diff --git a/objects/aVideoQueueEncoder.json.php b/objects/aVideoQueueEncoder.json.php
index 504f97b49..221c21954 100644
--- a/objects/aVideoQueueEncoder.json.php
+++ b/objects/aVideoQueueEncoder.json.php
@@ -1,182 +1,182 @@
error = true;
global $global, $config;
if (!isset($global['systemRootPath'])) {
require_once '../videos/configuration.php';
}
require_once $global['systemRootPath'] . 'objects/user.php';
require_once $global['systemRootPath'] . 'objects/video.php';
if (!User::canUpload()) {
$obj->msg = __("Permission denied");
die(json_encode($obj));
}
// A list of permitted file extensions
$allowed = array('mp4', 'avi', 'mov', 'mkv', 'flv', 'mp3', 'm4a', 'wav', 'm4v', 'webm', 'wmv');
if (isset($_FILES['upl']) && $_FILES['upl']['error'] == 0) {
$updateVideoGroups = false;
//echo "Success: \$_FILES OK\n";
$extension = pathinfo($_FILES['upl']['name'], PATHINFO_EXTENSION);
if (!in_array(strtolower($extension), $allowed)) {
//echo '{"status":"error", "msg":"File extension error [' . $_FILES['upl']['name'] . '], we allow only (' . implode(",", $allowed) . ')"}';
status(["status" => "error"
, "msg" => "File extension error (" . $_FILES['upl']['name'] . "), we allow only (" . implode(",", $allowed) . ")"]);
exit;
}
//echo "Success: file extension OK\n";
//chack if is an audio
$type = "video";
if (strcasecmp($extension, 'mp3') == 0 || strcasecmp($extension, 'wav') == 0 || strcasecmp($extension, 'm4a') == 0) {
$type = 'audio';
}
//var_dump($extension, $type);exit;
require_once $global['systemRootPath'] . 'objects/video.php';
//echo "Starting Get Duration\n";
$duration = Video::getDurationFromFile($_FILES['upl']['tmp_name']);
// check if can upload video (about time limit storage)
if (!empty($global['videoStorageLimitMinutes'])) {
$maxDuration = $global['videoStorageLimitMinutes'] * 60;
$currentStorageUsage = getSecondsTotalVideosLength();
$thisFile = parseDurationToSeconds($duration);
$limitAfterThisFile = $currentStorageUsage + $thisFile;
if ($maxDuration < $limitAfterThisFile) {
status(["status" => "error", "msg" => "Sorry, your storage limit has run out."
. "
[Max Duration: {$maxDuration} Seconds]"
. "
[Current Srotage Usage: {$currentStorageUsage} Seconds]"
. "
[This File Duration: {$thisFile} Seconds]"
. "
[Limit after this file: {$limitAfterThisFile} Seconds]", "type" => '$_FILES Limit Error']);
if (!empty($_FILES['upl']['videoId'])) {
$video = new Video("", "", $_FILES['upl']['videoId']);
$video->delete();
}
exit;
}
}
$path_parts = pathinfo($_FILES['upl']['name']);
if (empty($path_parts['extension']) || !in_array(strtolower($path_parts['extension']), $global['allowedExtension'])) {
_error_log("Extension not allowed File " . __FILE__ . ": " . json_encode($path_parts));
die();
}
$mainName = preg_replace("/[^A-Za-z0-9]/", "", cleanString($path_parts['filename']));
$filename = uniqid($mainName . "_YPTuniqid_", true);
$originalFilePath = Video::getStoragePath()."original_" . $filename;
$video = new Video(preg_replace("/_+/", " ", $path_parts['filename']), $filename, @$_FILES['upl']['videoId']);
$video->setDuration($duration);
if ($type == 'audio') {
$video->setType($type);
} else {
$video->setType("video");
}
- $video->setStatus('e');
+ $video->setStatus(Video::$statusEncoding);
/*
* set visibility for private videos
*/
if (array_key_exists('videoGroups', $_FILES['upl'])) {
$video->setVideoGroups($_FILES['upl']['videoGroups']);
$updateVideoGroups = true;
}
/*
* set description (if given)
*/
if (!empty($_FILES['upl']['description'])) {
$video->setDescription($_FILES['upl']['description']);
}
/*
* set title (if given)
*/
if (!empty($_FILES['upl']['title'])) {
$video->setTitle($_FILES['upl']['title']);
$video->setClean_title($_FILES['upl']['title']);
} else {
/**
* Make a better title and clean title
*/
$videoNewTitle = $video->getTitle();
$titleParts = explode("YPTuniqid", $videoNewTitle);
$video->setTitle($titleParts[0]);
$video->setClean_title($titleParts[0]);
}
$id = $video->save($updateVideoGroups);
/**
* Copy, rename or move original file
*
* copy: used from command line when -c option is included
* rename: used with files which were downloaded directly into the videos directory (from other media sites)
* move: default, used with uploaded files
*/
if (array_key_exists('copyOriginalFile', $_FILES['upl'])) {
if (!copy($_FILES['upl']['tmp_name'], $originalFilePath)) {
die("Error on copy(" . $_FILES['upl']['tmp_name'] . ", " . $originalFilePath . ")");
}
} elseif (array_key_exists('dontMoveUploadedFile', $_FILES['upl'])) {
if (!rename($_FILES['upl']['tmp_name'], $originalFilePath)) {
die("Error on rename(" . $_FILES['upl']['tmp_name'] . ", " . $originalFilePath . ")");
}
} elseif (!move_uploaded_file($_FILES['upl']['tmp_name'], $originalFilePath)) {
if (!rename($_FILES['upl']['tmp_name'], $originalFilePath)) {
die("Error on move_uploaded_file(" . $_FILES['upl']['tmp_name'] . ", " . $originalFilePath . ")");
}
}
$video = new Video('', '', $id);
// send to encoder
$queue = array();
$postFields = array();
if ($video->getType() == 'video') {
if (AVideoPlugin::isEnabledByName("VideoHLS")) {
$postFields['inputHLS'] = 1;
}else{
$postFields['inputLow'] = 1;
$postFields['inputSD'] = 1;
$postFields['inputHD'] = 1;
if (!empty($_FILES['upl']['webm']))
$postFields['webm'] = 1;
}
} else {
$postFields['audioOnly'] = 1;
$postFields['spectrum'] = 1;
}
if (!empty($_FILES['upl']['override_status']))
$postFields['override_status'] = $_FILES['upl']['override_status'];
if (!empty($_FILES['upl']['update_video_id']))
$postFields['update_video_id'] = $_FILES['upl']['update_video_id'];
$queue[] = $video->queue($postFields);
//exec("/usr/bin/php -f videoEncoder.php {$_FILES['upl']['tmp_name']} {$filename} 1> Video::getStoragePath()."{$filename}_progress.txt 2>&1", $output, $return_val);
//var_dump($output, $return_val);
//echo '{"status":"success", "msg":"Your video (' . $filename . ') is encoding
' . $cmd . '", "filename":"' . $filename . '", "duration":"' . $duration . '"}';
status(["status" => "success"
, "msg" => "Your video ($filename) is queue"
, "filename" => "$filename"
, "duration" => "$duration"
, "queue" => json_encode($queue)]);
//exit;
} else {
//echo '{"status":"error", "msg":' . json_encode($_FILES) . ', "type":"$_FILES Error"}';
status(["status" => "error", "msg" => print_r($_FILES, true), "type" => '$_FILES Error']);
//exit;
}
diff --git a/objects/getTimes.json.php b/objects/getTimes.json.php
index 71757441b..b65e2a988 100644
--- a/objects/getTimes.json.php
+++ b/objects/getTimes.json.php
@@ -1,14 +1,15 @@
_serverTime = time();
$obj->_serverDBTime = getDatabaseTime();
$obj->_serverTimeString = date('Y-m-d H:i:s');
$obj->_serverDBTimeString = date('Y-m-d H:i:s', getDatabaseTime());
+$obj->_serverTimezone = date_default_timezone_get();
die(json_encode($obj));
\ No newline at end of file
diff --git a/objects/user.php b/objects/user.php
index 319cc9cc9..f09233231 100644
--- a/objects/user.php
+++ b/objects/user.php
@@ -1,2370 +1,2395 @@
user = $user;
if ($password !== false) {
$this->password = $password;
} else {
$this->loadFromUser($user);
}
} else {
// get data from id
$this->load($id);
}
}
public function getEmail() {
return $this->email;
}
public function getUser() {
return $this->user;
}
public function getAbout() {
return str_replace(array('\\\\\\\n'), array("\n"), $this->about);
}
public function setAbout($about) {
$this->about = xss_esc($about);
}
public function getPassword() {
return $this->password;
}
public function getCanStream() {
return $this->canStream;
}
public function setCanStream($canStream) {
$this->canStream = (empty($canStream) || strtolower($canStream) === 'false') ? 0 : 1;
}
public function getCanViewChart() {
return $this->canViewChart;
}
public function setCanViewChart($canViewChart) {
$this->canViewChart = (empty($canViewChart) || strtolower($canViewChart) === 'false') ? 0 : 1;
}
public function getCanCreateMeet() {
return $this->canCreateMeet;
}
public function setCanCreateMeet($canCreateMeet) {
$this->canCreateMeet = (empty($canCreateMeet) || strtolower($canCreateMeet) === 'false') ? 0 : 1;
;
}
public function getCanUpload() {
return $this->canUpload;
}
public function setCanUpload($canUpload) {
$this->canUpload = (empty($canUpload) || strtolower($canUpload) === 'false') ? 0 : 1;
}
public function getAnalyticsCode() {
return $this->analyticsCode;
}
public function setAnalyticsCode($analyticsCode) {
preg_match("/(ua-\d{4,9}-\d{1,4})/i", $analyticsCode, $matches);
if (!empty($matches[1])) {
$this->analyticsCode = $matches[1];
} else {
$this->analyticsCode = "";
}
}
public function getAnalytics() {
$id = $this->getId();
$aCode = $this->getAnalyticsCode();
if (!empty($id) && !empty($aCode)) {
$code = "
";
} else {
$code = "";
}
return $code;
}
public function addExternalOptions($id, $value) {
$eo = unserialize(base64_decode($this->externalOptions));
if (!is_array($eo)) {
$eo = array();
}
$eo[$id] = $value;
$this->setExternalOptions($eo);
return $this->save();
}
public function removeExternalOptions($id) {
$eo = unserialize(base64_decode($this->externalOptions));
unset($eo[$id]);
$this->setExternalOptions($eo);
return $this->save();
}
public function setExternalOptions($options) {
//we convert it to base64 to sanitize the input since we do not validate input from externalOptions
$this->externalOptions = base64_encode(serialize($options));
}
public function getExternalOption($id) {
$eo = unserialize(base64_decode($this->externalOptions));
if (empty($eo[$id])) {
return null;
}
return $eo[$id];
}
private function load($id) {
$id = intval($id);
if (empty($id)) {
return false;
}
$user = self::getUserDb($id);
if (empty($user)) {
return false;
}
foreach ($user as $key => $value) {
$this->$key = $value;
}
return true;
}
private function loadFromUser($user) {
$userLoaded = self::getUserDbFromUser($user);
if (empty($userLoaded)) {
return false;
}
_error_log("User::loadFromUser($user) ");
_error_log("User::loadFromUser json " . json_encode(debug_backtrace()));
foreach ($userLoaded as $key => $value) {
$this->$key = $value;
}
return true;
}
public function loadSelfUser() {
$this->load($this->getId());
}
public static function getId() {
if (self::isLogged()) {
return $_SESSION['user']['id'];
} else {
return false;
}
}
public static function getEmail_() {
if (self::isLogged()) {
return $_SESSION['user']['email'];
} else {
return false;
}
}
public function getBdId() {
return $this->id;
}
public static function updateSessionInfo() {
if (self::isLogged()) {
$user = self::getUserDb($_SESSION['user']['id']);
$_SESSION['user'] = $user;
}
}
public static function getName() {
if (self::isLogged()) {
return $_SESSION['user']['name'];
} else {
return false;
}
}
public static function getUserName() {
if (self::isLogged()) {
return $_SESSION['user']['user'];
} else {
return false;
}
}
public static function getUserChannelName() {
if (self::isLogged()) {
if (empty($_SESSION['user']['channelName'])) {
$_SESSION['user']['channelName'] = self::_recommendChannelName();
$user = new User(User::getId());
$user->setChannelName($_SESSION['user']['channelName']);
$user->save();
}
return $_SESSION['user']['channelName'];
} else {
return false;
}
}
public static function _recommendChannelName($name = "", $try = 0, $unknown = "", $users_id = 0) {
if (empty($users_id)) {
if (!empty(User::getId())) {
$users_id = User::getId();
}
}
if (empty($users_id)) {
$newChannelName = $name . "_" . uniqid();
if (strlen($newChannelName) > 40) {
$newChannelName = uniqid();
}
return $newChannelName;
}
if ($try > 10) {
_error_log("User:_recommendChannelName too many tries ({$name}) (" . User::getId() . ") ", AVideoLog::$ERROR);
return uniqid();
}
if (empty($name)) {
$name = self::getNameIdentification();
if ($name == __("Unknown User") && !empty($unknown)) {
$name = $unknown;
}
$name = cleanString($name);
}
// in case is a email get only the username
$parts = explode("@", $name);
$name = $parts[0];
// do not exceed 36 chars to leave some room for the unique id;
$name = substr($name, 0, 36);
if (!Permissions::canAdminUsers()) {
$user = self::getUserFromChannelName($name);
if ($user && $user['id'] !== $users_id) {
return self::_recommendChannelName($name . "_" . uniqid(), $try + 1);
}
}
return $name;
}
public static function getUserFromChannelName($channelName) {
$channelName = cleanString($channelName);
global $global;
$channelName = ($channelName);
$sql = "SELECT * FROM users WHERE channelName = ? LIMIT 1";
$res = sqlDAL::readSql($sql, "s", array($channelName));
$user = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($user != false) {
$user = cleanUpRowFromDatabase($user);
return $user;
} else {
return false;
}
}
/**
* return an name to identify the user
* @return String
*/
public static function getNameIdentification() {
global $advancedCustomUser;
if (self::isLogged()) {
if (!empty(self::getName()) && empty($advancedCustomUser->doNotIndentifyByName)) {
return self::getName();
}
if (!empty(self::getMail()) && empty($advancedCustomUser->doNotIndentifyByEmail)) {
return self::getMail();
}
if (!empty(self::getUserName()) && empty($advancedCustomUser->doNotIndentifyByUserName)) {
return self::getUserName();
}
if (!empty(self::getUserChannelName())) {
return self::getUserChannelName();
}
}
return __("Unknown User");
}
/**
* return an name to identify the user from database
* @return String
*/
public function getNameIdentificationBd() {
global $advancedCustomUser;
if (!empty($this->name) && empty($advancedCustomUser->doNotIndentifyByName)) {
return $this->name;
}
if (!empty($this->email) && empty($advancedCustomUser->doNotIndentifyByEmail)) {
return $this->email;
}
if (!empty($this->user) && empty($advancedCustomUser->doNotIndentifyByUserName)) {
return $this->user;
}
if (!empty($this->channelName)) {
return $this->channelName;
}
return __("Unknown User");
}
public static function getNameIdentificationById($id = "") {
if (!empty($id)) {
$user = new User($id);
return $user->getNameIdentificationBd();
}
return __("Unknown User");
}
public static function getUserPass() {
if (self::isLogged()) {
return $_SESSION['user']['password'];
} else {
return false;
}
}
public function _getName() {
return $this->name;
}
public function getBdName() {
return $this->_getName();
}
public static function _getPhoto($id = "") {
global $global;
if (!empty($id)) {
$user = self::findById($id);
if (!empty($user)) {
$photo = $user['photoURL'];
}
} elseif (self::isLogged()) {
$photo = $_SESSION['user']['photoURL'];
}
if (!empty($photo)) {
if (preg_match("/videos\/userPhoto\/.*/", $photo) && file_exists($global['systemRootPath'] . $photo)) {
return $photo;
} else {
$photoPath = "/videos/userPhoto/photo{$id}.png";
$content = url_get_contents($photo);
file_put_contents($global['systemRootPath'] . $photoPath, $content);
$photo = $photoPath;
}
}
if (empty($photo)) {
$photo = "view/img/userSilhouette.jpg";
}
return $photo;
}
public static function getPhoto($id = "") {
global $global;
if (!empty($id)) {
$user = self::findById($id);
if (!empty($user)) {
$photo = $user['photoURL'];
}
} elseif (self::isLogged()) {
$photo = $_SESSION['user']['photoURL'];
}
if (!empty($photo) && preg_match("/videos\/userPhoto\/.*/", $photo)) {
if (file_exists($global['systemRootPath'] . $photo)) {
$photo = getCDN() . $photo . "?" . filemtime($global['systemRootPath'] . $photo);
} else {
$photo = "";
}
}
if (empty($photo)) {
$photo = getCDN() . "view/img/userSilhouette.jpg";
}
return $photo;
}
public static function _getOGImage($users_id) {
return "/videos/userPhoto/photo{$users_id}_og_200X200.jpg";
}
public static function deleteOGImage($users_id) {
global $global;
$photo = $global['systemRootPath'] . self::_getOGImage($users_id);
@unlink($photo);
}
public static function getOGImage($users_id = "") {
global $global;
$photo = self::_getPhoto($users_id);
if ($photo == "view/img/userSilhouette.jpg") {
return getCDN() . "view/img/userSilhouette.jpg";
}
if (empty($photo)) {
return false;
}
$source = $global['systemRootPath'] . $photo;
$destination = $global['systemRootPath'] . self::_getOGImage($users_id);
convertImageToOG($source, $destination);
return getCDN() . self::_getOGImage($users_id);
}
public static function getEmailVerifiedIcon($id = "") {
global $advancedCustomUser;
$mark = "";
if (!empty($advancedCustomUser->showEmailVerifiedMark)) {
if (!empty($id)) {
$user = self::findById($id);
if (!empty($user)) {
$verified = $user['emailVerified'];
}
} elseif (self::isLogged()) {
$verified = $_SESSION['user']['emailVerified'];
}
if (!empty($verified)) {
$mark .= ' ';
} else {
//return '';
$mark .= '';
}
}
if ($advancedCustomUser->Checkmark1Enabled) {
if (User::externalOptionsFromUserID($id, "checkmark1")) {
$mark .= " " . $advancedCustomUser->Checkmark1HTML;
}
}
if ($advancedCustomUser->Checkmark2Enabled) {
if (User::externalOptionsFromUserID($id, "checkmark2")) {
$mark .= " " . $advancedCustomUser->Checkmark2HTML;
}
}
if ($advancedCustomUser->Checkmark3Enabled) {
if (User::externalOptionsFromUserID($id, "checkmark3")) {
$mark .= " " . $advancedCustomUser->Checkmark3HTML;
}
}
return $mark;
}
public function getPhotoDB() {
global $global;
$photo = self::getPhoto($this->id);
return $photo;
}
public static function getBackground($id = "") {
global $global;
if (!empty($id)) {
$user = self::findById($id);
if (!empty($user)) {
$photo = $user['backgroundURL'];
}
} elseif (self::isLogged()) {
$photo = $_SESSION['user']['backgroundURL'];
}
if (!empty($photo) && preg_match("/videos\/userPhoto\/.*/", $photo)) {
if (file_exists($global['systemRootPath'] . $photo)) {
$photo = getCDN() . $photo;
} else {
$photo = "";
}
}
if (empty($photo)) {
$photo = getCDN() . "view/img/background.png";
}
return $photo;
}
public static function getMail() {
if (self::isLogged()) {
return $_SESSION['user']['email'];
} else {
return false;
}
}
public function save($updateUserGroups = false) {
global $global, $config, $advancedCustom, $advancedCustomUser;
if (is_object($config) && $config->currentVersionLowerThen('5.6')) {
// they dont have analytics code
return false;
}
if (empty($this->user) || empty($this->password)) {
//echo "u:" . $this->user . "|p:" . strlen($this->password);
_error_log('Error : ' . __("You need a user and passsword to register"));
return false;
}
if (empty($this->isAdmin)) {
$this->isAdmin = "false";
}
if (empty($this->canStream)) {
if (empty($this->id)) { // it is a new user
if (empty($advancedCustomUser->newUsersCanStream)) {
$this->canStream = "0";
} else {
$this->canStream = "1";
}
} else {
$this->canStream = "0";
}
}
if (empty($this->canUpload)) {
$this->canUpload = "0";
}
if (empty($this->status)) {
$this->status = 'a';
}
if (empty($this->emailVerified)) {
$this->emailVerified = "false";
}
$user = ($this->user);
$password = ($this->password);
$name = ($this->name);
$status = ($this->status);
$this->about = preg_replace("/(\\\)+n/", "\n", $this->about);
$this->channelName = self::_recommendChannelName($this->channelName, 0, $this->user, $this->id);
$channelName = ($this->channelName);
if (filter_var($this->donationLink, FILTER_VALIDATE_URL) === false) {
$this->donationLink = "";
}
if (!empty($this->id)) {
$formats = "ssssiiii";
$values = array($user, $password, $this->email, $name, $this->isAdmin, $this->canStream, $this->canUpload, $this->canCreateMeet);
$sql = "UPDATE users SET user = ?, password = ?, "
. "email = ?, name = ?, isAdmin = ?,"
. "canStream = ?,canUpload = ?,canCreateMeet = ?,";
if (isset($this->canViewChart)) {
$formats .= "i";
$values[] = $this->canViewChart;
$sql .= "canViewChart = ?, ";
}
$formats .= "ssssssissssssssssi";
$values[] = $this->status;
$values[] = $this->photoURL;
$values[] = $this->backgroundURL;
$values[] = $this->recoverPass;
$values[] = $this->about;
$values[] = $this->channelName;
$values[] = $this->emailVerified;
$values[] = $this->analyticsCode;
$values[] = $this->externalOptions;
$values[] = $this->first_name;
$values[] = $this->last_name;
$values[] = $this->address;
$values[] = $this->zip_code;
$values[] = $this->country;
$values[] = $this->region;
$values[] = $this->city;
$values[] = $this->donationLink;
$values[] = $this->id;
$sql .= "status = ?, "
. "photoURL = ?, backgroundURL = ?, "
. "recoverPass = ?, about = ?, "
. " channelName = ?, emailVerified = ? , analyticsCode = ?, externalOptions = ? , "
. " first_name = ? , last_name = ? , address = ? , zip_code = ? , country = ? , region = ? , city = ? , donationLink = ? , "
. " modified = now() WHERE id = ?";
} else {
$formats = "ssssiiiissssss";
$values = array($user, $password, $this->email, $name, $this->isAdmin, $this->canStream, $this->canUpload, $this->canCreateMeet,
$status, $this->photoURL, $this->recoverPass, $channelName, $this->analyticsCode, $this->externalOptions);
$sql = "INSERT INTO users (user, password, email, name, isAdmin, canStream, canUpload, canCreateMeet, canViewChart, status,photoURL,recoverPass, created, modified, channelName, analyticsCode, externalOptions) "
. " VALUES (?,?,?,?,?,?,?,?, false, "
. "?,?,?, now(), now(),?,?,?)";
}
$insert_row = sqlDAL::writeSql($sql, $formats, $values);
if ($insert_row) {
if (empty($this->id)) {
$id = $global['mysqli']->insert_id;
if (!empty($advancedCustomUser->unverifiedEmailsCanNOTLogin)) {
self::sendVerificationLink($id);
}
} else {
$id = $this->id;
}
if ($updateUserGroups) {
require_once $global['systemRootPath'] . 'objects/userGroups.php';
// update the user groups
UserGroups::updateUserGroups($id, $this->userGroups);
}
return $id;
} else {
_error_log(' Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error . " $sql");
return false;
}
}
public static function getChannelOwner($channelName) {
global $global;
$channelName = ($channelName);
$sql = "SELECT * FROM users WHERE channelName = ? LIMIT 1";
$res = sqlDAL::readSql($sql, "s", array($channelName));
$result = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res) {
$result = cleanUpRowFromDatabase($result);
$user = $result;
} else {
$user = false;
}
return $user;
}
public static function getFromUsername($user) {
global $global;
$user = ($user);
$sql = "SELECT * FROM users WHERE user = ? LIMIT 1";
$res = sqlDAL::readSql($sql, "s", array($user));
$result = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res) {
$result = cleanUpRowFromDatabase($result);
$user = $result;
} else {
$user = false;
}
return $user;
}
private static function setCacheWatchVideo($cacheName, $value) {
if (!User::isLogged()) {
ObjectYPT::setCache($cacheName, $value);
;
} else {
ObjectYPT::setSessionCache($cacheName, $value);
}
}
public static function canWatchVideo($videos_id) {
$cacheName = "canWatchVideo$videos_id";
if (!User::isLogged()) {
$cacheName = "canWatchVideoNOTLOGED$videos_id";
$cache = ObjectYPT::getCache($cacheName, 3600);
} else {
$cache = ObjectYPT::getSessionCache($cacheName, 600);
}
if (isset($cache)) {
if($cache === 'false'){
$cache = false;
}
return $cache;
}
if (empty($videos_id)) {
_error_log("User::canWatchVideo Video is empty ({$videos_id})");
return false;
}
if (User::isAdmin()) {
return true;
}
$video = new Video("", "", $videos_id);
if ($video->getStatus() === 'i') {
_error_log("User::canWatchVideo Video is inactive ({$videos_id})");
self::setCacheWatchVideo($cacheName, false);
return false;
}
$user = new User($video->getUsers_id());
if ($user->getStatus() === 'i') {
_error_log("User::canWatchVideo User is inactive ({$videos_id})");
self::setCacheWatchVideo($cacheName, false);
return false;
}
if (AVideoPlugin::userCanWatchVideo(User::getId(), $videos_id)) {
self::setCacheWatchVideo($cacheName, true);
return true;
}
// check if the video is not public
$rows = UserGroups::getVideoGroups($videos_id);
if (empty($rows)) {
// check if any plugin restrict access to this video
if (!AVideoPlugin::userCanWatchVideo(User::getId(), $videos_id)) {
if (User::isLogged()) {
_error_log("User::canWatchVideo there is no usergorup set for this video but A plugin said user [" . User::getId() . "] can not see ({$videos_id})");
} else {
_error_log("User::canWatchVideo there is no usergorup set for this video but A plugin said user [not logged] can not see ({$videos_id})");
}
self::setCacheWatchVideo($cacheName, false);
return false;
} else {
self::setCacheWatchVideo($cacheName, true);
return true; // the video is public
}
}
if (!User::isLogged()) {
_error_log("User::canWatchVideo You are not logged so can not see ({$videos_id}) session_id=" . session_id() . " SCRIPT_NAME=" . $_SERVER["SCRIPT_NAME"] . " IP = " . getRealIpAddr());
self::setCacheWatchVideo($cacheName, false);
return false;
}
// if is not public check if the user is on one of its groups
$rowsUser = UserGroups::getUserGroups(User::getId());
foreach ($rows as $value) {
foreach ($rowsUser as $value2) {
if ($value['id'] === $value2['id']) {
self::setCacheWatchVideo($cacheName, true);
return true;
}
}
}
_error_log("User::canWatchVideo The user " . User::getId() . " is not on any of the user groups ({$videos_id}) " . json_encode($rows));
self::setCacheWatchVideo($cacheName, false);
return false;
}
public static function canWatchVideoWithAds($videos_id) {
if (empty($videos_id)) {
_error_log("User::canWatchVideo (videos_id is empty) " . $videos_id);
return false;
}
if (User::isAdmin()) {
return true;
}
if (AVideoPlugin::userCanWatchVideoWithAds(User::getId(), $videos_id)) {
//_error_log("User::userCanWatchVideoWithAds (can) " . User::getId() . " " . $videos_id);
return true;
}
_error_log("User::userCanWatchVideoWithAds (No can not) " . User::getId() . " " . $videos_id);
if (self::canWatchVideo($videos_id)) {
//_error_log("User::canWatchVideo (can) " . $videos_id);
return true;
}
_error_log("User::canWatchVideo (No can not) " . $videos_id);
return false;
}
public function delete() {
if (!self::isAdmin()) {
return false;
}
// cannot delete yourself
if (self::getId() === $this->id) {
return false;
}
global $global;
if (!empty($this->id)) {
$sql = "DELETE FROM users WHERE id = ?";
} else {
return false;
}
return sqlDAL::writeSql($sql, "i", array($this->id));
}
const USER_LOGGED = 0;
const USER_NOT_VERIFIED = 1;
const USER_NOT_FOUND = 2;
const CAPTCHA_ERROR = 3;
const REQUIRE2FA = 4;
public function login($noPass = false, $encodedPass = false, $ignoreEmailVerification = false) {
if (User::isLogged()) {
return false;
}
global $global, $advancedCustom, $advancedCustomUser, $config;
if (strtolower($encodedPass) === 'false') {
$encodedPass = false;
}
//_error_log("user::login: noPass = $noPass, encodedPass = $encodedPass, this->user, $this->user " . getRealIpAddr());
if ($noPass) {
$user = $this->find($this->user, false, true);
} else {
$user = $this->find($this->user, $this->password, true, $encodedPass);
}
if (!self::checkLoginAttempts()) {
return self::CAPTCHA_ERROR;
}
ObjectYPT::clearSessionCache();
_session_start();
// check for multiple logins attempts to prevent hacking end
// if user is not verified
if (empty($ignoreEmailVerification) && !empty($user) && empty($user['isAdmin']) && empty($user['emailVerified']) && !empty($advancedCustomUser->unverifiedEmailsCanNOTLogin)) {
unset($_SESSION['user']);
self::sendVerificationLink($user['id']);
return self::USER_NOT_VERIFIED;
} elseif ($user) {
$_SESSION['user'] = $user;
$this->setLastLogin($_SESSION['user']['id']);
$rememberme = 0;
if ((!empty($_POST['rememberme']) && $_POST['rememberme'] == "true") || !empty($_COOKIE['rememberme'])) {
$expires = strtotime("+ 1 year");
$rememberme = 1;
} else {
$expires = 0;
}
_setcookie("rememberme", $rememberme, $expires);
_setcookie("user", $user['user'], $expires);
_setcookie("pass", $user['password'], $expires);
AVideoPlugin::onUserSignIn($_SESSION['user']['id']);
$_SESSION['loginAttempts'] = 0;
session_write_close();
return self::USER_LOGGED;
} else {
unset($_SESSION['user']);
return self::USER_NOT_FOUND;
}
}
public static function isCaptchaNeed() {
global $advancedCustomUser;
// check for multiple logins attempts to prevent hacking
if (!empty($_SESSION['loginAttempts']) && !empty($advancedCustomUser->requestCaptchaAfterLoginsAttempts)) {
if (isMobile()) {
$advancedCustomUser->requestCaptchaAfterLoginsAttempts += 10;
}
if ($_SESSION['loginAttempts'] > $advancedCustomUser->requestCaptchaAfterLoginsAttempts) {
return true;
}
}
return false;
}
public static function checkLoginAttempts() {
global $advancedCustomUser, $global;
// check for multiple logins attempts to prevent hacking
if (empty($_SESSION['loginAttempts'])) {
_session_start();
$_SESSION['loginAttempts'] = 0;
}
if (!empty($advancedCustomUser->requestCaptchaAfterLoginsAttempts)) {
_session_start();
$_SESSION['loginAttempts']++;
if ($_SESSION['loginAttempts'] > $advancedCustomUser->requestCaptchaAfterLoginsAttempts) {
if (empty($_POST['captcha'])) {
return false;
}
require_once $global['systemRootPath'] . 'objects/captcha.php';
if (!Captcha::validation($_POST['captcha'])) {
return false;
}
}
}
return true;
}
public static function getCaptchaFormIfNeed() {
// check for multiple logins attempts to prevent hacking
if (self::isCaptchaNeed()) {
return self::getCaptchaForm();
}
return "";
}
public static function getCaptchaForm($uid = "") {
global $global;
return '
';
echo htmlentities($frm);
?>
You can get notified for the new video uploads with the Webhook in the Notification plugin, Check here for more details
getMethod($method_name)->getDocComment();
$comment = str_replace(array('{webSiteRootURL}', '{getOrSet}', '{APIName}', '{APISecret}'), array($global['webSiteRootURL'], $matches[1], $matches[2], $obj->APISecret), $comment);
preg_match_all('#\bhttps?://[^,\s()<>]+(?:\([\w\d]+\)|([^,[:punct:]\s]|/))#', $comment, $match2);
//var_dump($match2[0]);
$link = "" . htmlentities($match2[0][0]) . "";
$comment = str_replace(array($match2[0][0], " *"), array($link, "*"), $comment);
echo ($comment);
//{webSiteRootURL}plugin/API/{getOrSet}.json.php?name={name}
?>
" . implode(" or ", $names) . "";
}
public function getName() {
return "PlayerSkins";
}
public function getUUID() {
return "e9a568e6-ef61-4dcc-aad0-0109e9be8e36";
}
public function getPluginVersion() {
return "1.1";
}
public function getEmptyDataObject() {
global $global;
$obj = new stdClass();
$obj->skin = "avideo";
$obj->playbackRates = "[0.5, 1, 1.5, 2]";
$obj->playerCustomDataSetup = "";
$obj->showSocialShareOnEmbed = true;
$obj->showLoopButton = true;
$obj->showLogo = false;
$obj->showShareSocial = true;
$obj->showLogoOnEmbed = false;
$obj->showLogoAdjustScale = "0.4";
$obj->showLogoAdjustLeft = "-74px";
$obj->showLogoAdjustTop = "-22px;";
$obj->disableEmbedTopInfo = false;
$obj->contextMenuDisableEmbedOnly = false;
$obj->contextMenuLoop = true;
$obj->contextMenuCopyVideoURL = true;
$obj->contextMenuCopyVideoURLCurrentTime = true;
$obj->contextMenuCopyEmbedCode = true;
$obj->contextMenuShare = true;
$obj->playerFullHeight = false;
return $obj;
}
static function getMediaTag($filename, $htmlMediaTag = false) {
global $autoPlayURL, $global, $config, $isVideoTypeEmbed;
$obj = AVideoPlugin::getObjectData('PlayerSkins');
$html = '';
if (empty($htmlMediaTag)) {
$video = Video::getVideoFromFileName($filename, true);
$vType = Video::getIncludeType($video);
$_GET['isMediaPlaySite'] = $video['id'];
if (!empty($video['externalOptions']->videoStartSeconds)) {
$video['externalOptions']->videoStartSeconds = parseDurationToSeconds($video['externalOptions']->videoStartSeconds);
} else {
$video['externalOptions']->videoStartSeconds = 0;
}
$images = Video::getImageFromFilename($filename);
if ($vType == 'video') {
$htmlMediaTag = '';
} else if ($vType == 'audio') {
$htmlMediaTag = '';
} else if ($vType == 'embed') {
$disableYoutubeIntegration = false;
if (!empty($advancedCustom->disableYoutubePlayerIntegration)) {
$disableYoutubeIntegration = true;
}
$_GET['isEmbedded'] = "";
if (((strpos($video['videoLink'], "youtu.be") == false) && (strpos($video['videoLink'], "youtube.com") == false) && (strpos($video['videoLink'], "vimeo.com") == false)) || ($disableYoutubeIntegration)) {
$_GET['isEmbedded'] = "e";
$isVideoTypeEmbed = 1;
$url = parseVideos($video['videoLink']);
if ($config->getAutoplay()) {
$url = addQueryStringParameter($url, 'autoplay', 1);
}
$htmlMediaTag = "";
$htmlMediaTag .= '';
$htmlMediaTag .= '';
} else {
// youtube!
if ((stripos($video['videoLink'], "youtube.com") != false) || (stripos($video['videoLink'], "youtu.be") != false)) {
$_GET['isEmbedded'] = "y";
} else if ((stripos($video['videoLink'], "vimeo.com") != false)) {
$_GET['isEmbedded'] = "v";
}
$_GET['isMediaPlaySite'] = $video['id'];
PlayerSkins::playerJSCodeOnLoad($video['id'], @$video['url']);
$htmlMediaTag = "";
$htmlMediaTag .= '';
$htmlMediaTag .= '';
}
} else if ($vType == 'serie') {
$isVideoTypeEmbed = 1;
$link = "{$global['webSiteRootURL']}plugin/PlayLists/embed.php";
$link = addQueryStringParameter($link, 'playlists_id', $video['serie_playlists_id']);
$link = addQueryStringParameter($link, 'autoplay', $config->getAutoplay());
$link = addQueryStringParameter($link, 'playlist_index', @$_REQUEST['playlist_index']);
$htmlMediaTag = "";
$htmlMediaTag .= '';
$htmlMediaTag .= '';
$htmlMediaTag .= '';
}
$html .= "';
}
$col1Classes = 'col-md-2 firstC';
$col2Classes = 'col-md-8 secC';
$col3Classes = 'col-md-2 thirdC';
if($obj->playerFullHeight){
$col2Classes .= ' text-center playerFullHeight';
}
$html .= '
' . $subscribe . '